package cn.com.cmbc.service;

import cn.com.cmbc.dto.FileDTO;
import cn.com.cmbc.utils.FileUtil;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class FileService {
    private static final Logger LOG = LoggerFactory.getLogger(FileService.class);

    private FileDTO createFileDTO(Path entry) throws IOException {
        BasicFileAttributes attrs = Files.readAttributes(entry, BasicFileAttributes.class);
        long size = attrs.isDirectory() ? FileUtil.getDirectorySize(entry) : attrs.size();
        String rowkeyId = FileUtil.encodeFileName(entry.getFileName().toString(), 10)
                +"~"+ FileUtil.encodeFileSize(size, 10)
                +"~"+ attrs.lastModifiedTime().toMillis();

        return new FileDTO(entry.getFileName().toString(),
                attrs.lastModifiedTime().toMillis(),
                attrs.isDirectory() ? "Directory" : "File",
                FileUtil.getFileExtension(entry.getFileName().toString()),
                size,
                entry.toAbsolutePath().toString(),
                rowkeyId);
    }

    private String fileList2JSON(List<FileDTO> fileList) {
        Gson gson = new Gson();
//         转换为 JSON 字符串
//        StringBuilder sb = new StringBuilder();
//        sb.append("[");
//        for (int i = 0; i < fileList.size(); i++) {
//            gson.toJson(fileList.get(i), sb);
//            sb.append(fileList.get(i).toJSON());
//            if (i < fileList.size() - 1) {
//                sb.append(",");
//            }
//        }
//        sb.append("]");
//        return sb.toString();
        return gson.toJson(fileList);
    }


    public String getPathFileJSON(String path) {

        // 对路径进行合法性检查
        Path startPath = Paths.get(path);

        List<FileDTO> fileList = new ArrayList<>();

        //列出路径下所有文件包含目录
        try (Stream<Path> stream = Files.walk(startPath)) {
            stream.forEach(entry -> {
                try {
                    FileDTO fileDTO = createFileDTO(entry);
                    fileList.add(fileDTO);
                    LOG.info("已添加文件：{}",fileDTO);

                } catch (IOException e) {
                    System.err.println("Error getting file attributes for " + entry);
                }
            });
        } catch (IOException e) {
            System.err.println("Error walking the file tree starting at " + startPath);
        }

        // 转换为 JSON 字符串
        String jsonString = fileList2JSON(fileList);

        return jsonString;

    }
}
